package Concurrency2.Chapter03_CAS_Atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * Instruction：实现对数组元素的操作是原子的
 * Author：@author MaLi
 */
public class T04_AtomicIntegerArray {
    public static void main(String[] args) throws InterruptedException {
        int[] arr = {0, 0, 0, 0, 0};
        AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(arr);
        //使用10个线程, 并发操作1000次每一个变量
        //通过一个变量记录是否有操作失败的情况
        AtomicInteger faliure = new AtomicInteger(0);
        ExecutorService service = Executors.newFixedThreadPool(10);
        CountDownLatch latch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            service.submit(() -> {
                //对数组的元素自增1
                for (int j = 0; j < arr.length; j++) {
                    for (int x = 0; x < 1000; x++) {
                        atomicIntegerArray.incrementAndGet(j);
                    }
                }
                latch.countDown();
            });
        }
        latch.await();
        System.out.println(atomicIntegerArray.toString());
        service.shutdownNow();
    }
}
